<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace app\library\Points;


use Yii;

/**
 * Description of Db
 *
 * @author wangchanghong
 */
class Db extends Base{
    
    //事务句柄
    protected $tr = null;
    
    protected function queryOne($sql){
        return Yii::$app->db->createCommand($sql)->queryOne();
    }
    
    protected function queryAll($sql){
        return Yii::$app->db->createCommand($sql)->queryAll();
    }
    
    protected function query($sql){
        return Yii::$app->db->createCommand($sql)->execute();
    }
    
    protected function insert($table, $data){
        Yii::$app->db->createCommand()->insert($table, $data)->execute();
        return Yii::$app->db->lastInsertID;
    }
    
    protected function update($table, $data, $where){
        Yii::$app->db->createCommand()->update($table, $data, $where)->execute();
    }

    /**
     * 开启事务
     */
    protected function beginTransaction(){
        if($this->tr) return;
        $this->tr = Yii::$app->db->beginTransaction();
    }
    
    /**
     * 提交事务
     */
    protected function commit(){
        if(!$this->tr) return;
        $this->tr->commit();
        $this->tr = null;
    }

    /**
     * 回滚事务
     */
    protected function rollBack(){
        if(!$this->tr) return;
        $this->tr->rollBack();
        $this->tr = null;
    }
    
    function __destruct() {
        $this->rollBack();
    }
}
